import React, { PropTypes, Component } from 'react';
import {myAjaxJson, ROOTURL, getAdminInfo} from './../publicAPI/publicAPI';

import fetch from 'isomorphic-fetch'
import Table from './Table'

const SHOW_ALL = '显示全部';
const SHOW_SOME = '仅显示提现';

class WithdrawRecord extends Component {
    //初始化
    constructor(props) {
        super(props)

        this.state = {
            customers: {},
            records: {},
            page: 1,    　　　　　//当前页码从1 开始
            buttonMsg: SHOW_SOME
        } // 初始化状态

        this.rHeight = window.innerHeight - 55
        this.selectShowWithdrow = null;
        this.searchCustomerBallog = null;
        this.accountIds = []; //已获取的用户数据
    }
    componentWillMount() {
        this.initPageStatus()
        let adminInfo = JSON.parse(sessionStorage.getItem("adminInfo"));
        if (!adminInfo) {
            getAdminInfo(() => {
                this.getWithdrawRecord();
            });
        } else {
            this.getWithdrawRecord();
        }
    }

    initPageStatus() {
        this.start = 0;
        this.limit = 10;

        this.nextPage = true;  //下一页
        this.prePage  = false;  //上一页
        this.maxPage = -1;

    }

    addZero(val) {
        return val>9?val : '0' + val;
    }

    //毫秒数转换时间 ps: 2016.09.08 10:30:22
    tmToFormatTimePoint(time) {
        if (time) {
            let date = new Date(+time);
            let MM = this.addZero(date.getMonth() + 1);
            let dd = this.addZero(date.getDate());
            let hh = this.addZero(date.getHours());
            let mm = this.addZero(date.getMinutes());
            let ss = this.addZero(date.getSeconds());
            return `${date.getFullYear()}.${MM}.${dd}  ${hh}:${mm}:${ss}`
        } else {
            return '';
        }
    }

    generateBallogParams() {
        let params = {
            start: this.start,
            limit: this.limit,
            order: [
                ['t', 'DESC']
            ]
        }
        if (this.selectShowWithdrow) {
            params =　Object.assign(params, this.selectShowWithdrow);
        }

　　　　　if (this.searchCustomerBallog) {
             params.where = Object.assign({}, params.where, this.searchCustomerBallog);
        }
        return params;
    }
    //获取客户提成信息
    getWithdrawRecord() {
         if (this.limit === 0) {
             return;
         }
         let params = this.generateBallogParams();
         myAjaxJson(ROOTURL + 'curacnt/ballog/search.api', 'POST', params,
             (json) => {
                 let record = [];
                 let acoIds = [];
                 json.forEach((item) => {
                     item.t  = this.tmToFormatTimePoint(item.t)
                     record.push(item)
                     if (this.accountIds.indexOf(item.accountId) === -1) {
                         acoIds.push(item.accountId);
                         this.accountIds.push(item.accountId)
                     }
                 })

                 let currentPage = Math.floor(this.start / this.limit) + 1;

                 if (json.length < this.limit) {
                      this.nextPage = false;
                      this.maxPage = currentPage;
                      this.limit = 0;
                 } else {
                      this.start += this.limit;
                 }
                 if (this.start !== this.limit) {
                     this.setState({
                         records: Object.assign({}, this.state.records, {[currentPage]: record}),
                         page: currentPage
                     })
                 } else {
                     this.setState({
                         records: {[currentPage]: record},
                         page: currentPage
                     })
                 }

                 if (!this.searchCustomerBallog) {
                     this.getAccountSearch(acoIds);
                 }
             }, (error) => {
                  alert('获取客户提成记录失败')
             })
    }

    getAccountSearch(accountIds) {
        if (accountIds.length > 0) {
            myAjaxJson(ROOTURL + 'grip/account/search.api', 'POST', {
                where: {
                    id: [
                        ['in', accountIds]
                    ]
                }
            }, (data) => {
                let customerIds = [];
                let accountInfo = {}
                for (let aco of data) {
                    accountInfo[aco.possessorId] = aco.id;
                    customerIds.push(aco.possessorId);
                }
                this.getCustomerInfo(customerIds, accountInfo)
            })
        }
    }

    //获取客户普通信息 昵称电话等
    getCustomerInfo(cusIds, accountInfo) {
        if (cusIds.length <= 0) return;

        myAjaxJson(ROOTURL + 'customer/profile/search.api', 'POST', {
            where: {
                id: [
                    ['in', cusIds]
                ]
            }
        }, (data) => {
            let customers = {};
            for (let cus of data) {
                let accountId = accountInfo[cus.id];
                customers[accountId] = {
                    id: cus.id,
                    accountId: accountId,
                    phone: cus.phone,
                    dname: cus.dname
                }
            }
            this.setState({
                customers: Object.assign({}, this.state.customers, customers)
            })
        })
    }

    findCustomer(dname, phone) {
        this.initPageStatus();
        this.searchCustomerBallog = null;
        if (dname == "" && phone == "") {
            this.getWithdrawRecord();
            return ;
        }

        let params = {
            where: {}
        }

        if (dname != "") {
            params.where.dname = [['eq', dname]];
        }
        if (phone != "") {
            params.where.phone = [['eq', phone]];
        }

        myAjaxJson(ROOTURL + 'customer/profile/search.api', 'POST', params,
           (data) => {
            let customers = {};
            let customerIds = [];
            for (let cus of data) {
                customers[cus.id] = {
                    id: cus.id,
                    phone: cus.phone,
                    dname: cus.dname
                }
                customerIds.push(cus.id);
            }
            this.searchAccounts(customerIds, customers)
        })
    }

    searchAccounts(cusIds, customerInfos) {
        if (cusIds.length > 0) {
            myAjaxJson(ROOTURL + 'grip/account/search.api', 'POST',{
                    where: {
                        possessorId: [['in', cusIds]]
                    }
                },(json) => {

                    let customers = {};
                    let acoIds = [];
                    for (let aco of json) {
                        let accountId = aco.id;
                        acoIds.push(accountId);
                        if (this.accountIds.indexOf(accountId) === -1) {
                            customers[accountId] = customerInfos[aco.possessorId]
                            customers[accountId].accountId = accountId
                            this.accountIds.push(accountId)
                        }
                    }
                    this.setState({
                        customers: Object.assign({}, this.state.customers, customers)
                    })
                    this.searchCustomerBallog = {
                            accountId: [['in', acoIds]]
                    }
                    this.getWithdrawRecord();
                }, (error) => {
                     alert('获取客户提成数据失败')
                })
        } else {
            this.nextPage = false;
            this.maxPage = 1;
            this.limit = 0;
            this.searchCustomerBallog = {
                    accountId: [['in', [0]]]
            }
            this.setState({
                records: {},
                page: 1
            })
        }
    }

    //查找接口
    handleSearchClick(e) {
        let dname=this.refs.dname.value;
        let phone=this.refs.phone.value;
        this.findCustomer(dname,phone);
    }

    showWithdraw() {
        this.initPageStatus();
        if (!this.selectShowWithdrow) {
            this.selectShowWithdrow = {
                where: {
                    b1: [['eq', 0]]
                }
            }
            this.setState({
                buttonMsg: SHOW_ALL
            })
        } else {
            this.selectShowWithdrow = null;
            this.setState({
                buttonMsg: SHOW_SOME
            })
        }
        this.getWithdrawRecord();
    }

    //翻页按钮
	handlePageClick(e) {//1为下一页，2为上一页
		const _buttonValue = e.target.value

        if (_buttonValue == 1) this.prePage = true;
        if (_buttonValue == 2) this.nextPage = true;

        let nextPage  = _buttonValue == 1? this.state.page + 1 : this.state.page - 1;
        if (nextPage == 1) this.prePage = false;
        if (nextPage == this.maxPage) this.nextPage = false;


        if (this.state.records[nextPage]) {
            this.setState({
                page: nextPage
            })
        } else if (nextPage > 0) {
            this.getWithdrawRecord();
        }
	}

    //render thead
    tHead() {
        let data = [
            { name: "id" },
            { name: "昵称" },
            { name: "电话号码" },
            { name:　"动户金额"},
            { name:　"动户后户值"},
            { name:　"时间"}
        ]
        const _width = {
                "0": "10%",
                "1": "3０%",
                "2": "2０%",
                "3": "1０%",
                "4": "1０%",
                "5": "20%"
        }

     	return data.map((item, index) => {
            return <th style = {{ width: _width[index] }}
                        role = "1"
                        key = {index}> {item.name} </th>
        })
    }

    tBody() {
         let _data = this.state.records[this.state.page];
         let customers = this.state.customers;
         if (_data) {
             return _data.map(item => {
                    let cus = customers[item.accountId];
                    return( <tr key = { item.id }>
                         <td> { cus ? cus.id : ''} </td>
                         <td> { cus ? cus.dname : ''} </td>
                         <td> { cus ? cus.phone : ''} </td>
                         <td> {(item.al).toFixed(2)} </td>
                         <td> {(item.b1).toFixed(2)} </td>
                         <td> {item.t} </td>
                     </tr>)
            });
        } else {
            return null;
        }
    }

    render() {

        return (
            <div className="right-wapper" style={{height: this.rHeight}}>
                <div className="rt-wrap rt-wrap-header">
                    <div className="input-div pr">
                        <label>昵称：</label>
                        <input type="text" placeholder="请输入要查找的微信号" className="default-text"
                           ref="dname"/>
                    </div>
                    <div className="input-div">
                        <label>电话号码：</label>
                        <input type="text" placeholder="请输入要查找的电话号码" className="default-text"
                           ref="phone" />
                    </div>
                    <div className="input-div">
                        <button className="search-btn" onClick={(e) => this.handleSearchClick(e)}>查找</button>
                        <button className="search-btn" onClick={(e) => this.showWithdraw(e)}>{this.state.buttonMsg}</button>
                    </div>

                </div>

                <div className="rt-wrap">
                    <h3 className="catagory">
                        <span className="cata-title">客户列表</span>
                        <button style={{display: this.nextPage ? "block" : "none"}} className="next" value="1" onClick={(e) => this.handlePageClick(e)}></button>
                        <button style={{display: this.prePage ? "block" : "none"}}  className="prev" value="2" onClick={(e) => this.handlePageClick(e)}></button>
                    </h3>
                    <Table tHead={this.tHead.call(this)} tBody={this.tBody.bind(this)()}/>
                </div>
            </div>
        );
    }
}
export default WithdrawRecord;
